/** @format */

import { defineStore } from "pinia";
import { loginApi } from "@/service/api";

export const useUser = defineStore("user", {
  state() {
    return {
      user: {},
      token: "",
    };
  },
  actions: {
    async login(form: any) {
      const { data } = await loginApi(form);
      if (data.value.code !== 201) {
        ElMessage.error(data.value.msg);
        return Promise.resolve(false);
      }
      if (data.value?.errors && data.value.errors.length > 0) {
        const errorMsg = data.value.errors.map((item: any) => item.msg).toString();
        return ElMessage.error(errorMsg);
      }
      ElMessage.success(data.value.msg);
      this.user = data.value.data;
      this.token = data.value.data.token;
      localStorage.setItem("web-user", JSON.stringify(this.user));
      localStorage.setItem("token", this.token);
      location.reload();
      return Promise.resolve(true);
    },
  },
});
